package cmd

import (
	"runtime"
	"os/exec"
	"bufio"
)


func ExecCmd(cmd_str string) (string, error){
	var out string;

	// 执行单个shell命令时, 直接运行即可
	var cmd *exec.Cmd
	if "windows" == runtime.GOOS {
		cmd = exec.Command("cmd", "/C", cmd_str)
	}else{
		cmd = exec.Command("/bin/bash", "-c", cmd_str)
	}

	//创建获取命令输出管道
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return "", err
	}

	//执行命令
	if err := cmd.Start(); err != nil {
		return "", err
	}

	//使用带缓冲的读取器
	outputBuf := bufio.NewReader(stdout)

	for {

		//一次获取一行,_ 获取当前行是否被读完
		out1, _, err := outputBuf.ReadLine()
		out = out + string(out1) + "\n"
		if err != nil {
			return out,nil
		}
	}

	//wait 方法会一直阻塞到其所属的命令完全运行结束为止
	if err := cmd.Wait(); err != nil {
		return "",err
	}
	return out, nil
}